package com.ct.system.start.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ct.common.utils.R;
import com.ct.system.start.dao.QueryMapper;
import com.ct.system.start.service.QueryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service("queryService")
public class QueryServiceImpl implements QueryService {

    @Autowired
    private QueryMapper queryMapper;

    @Override
    public R queryTemplate(String nodeName) {
        QueryWrapper<Map<String, Object>> qw = new QueryWrapper<>();
        qw.like("fun_name",nodeName);
        List<Map<String, Object>> maps = queryMapper.queryTemplate(qw);
        return R.ok().put("data", maps);
    }

    @Override
    public R queryComponent(String dataClass) {
        List<Map<String, Object>> maps = null;
        if(dataClass != null){
            String[] ss = dataClass.split("\\.");
            if(ss != null && ss.length == 2){
                QueryWrapper<Map<String, Object>> qw = new QueryWrapper<>();
                qw.eq("namespace",ss[0]).eq("upper(name)", ss[1].toUpperCase()).eq("versiontype","0");
                maps = queryMapper.queryComponent(qw);
                if(maps == null || maps.size() == 0){ // 第2次查询
                    QueryWrapper<Map<String, Object>> qw2 = new QueryWrapper<>();
                    qw2.likeRight("LOWER(NAME)", ss[1].toLowerCase());
                    maps = queryMapper.queryComponent3(qw2);
                }
                if(maps == null || maps.size() == 0){ // 第3次查询
                    QueryWrapper<Map<String, Object>> qw3 = new QueryWrapper<>();
                    qw3.likeRight("table_name", ss[0].toUpperCase() + "_" + ss[1].toUpperCase());
                    maps = queryMapper.queryComponent2(qw3);
                }
                if(maps == null || maps.size() == 0){ // 第4次查询
                    QueryWrapper<Map<String, Object>> qw4 = new QueryWrapper<>();
                    qw4.likeRight("table_name", ss[1].toUpperCase());
                    maps = queryMapper.queryComponent2(qw4);
                }
                if(maps == null || maps.size() == 0){ // 第5次查询
                    QueryWrapper<String> qw5 = new QueryWrapper<>();
                    qw5.likeRight("table_name", ss[0].toUpperCase() + "_" + ss[1].toUpperCase());
                    List<String> list = queryMapper.queryDBTableName(qw5);
                    if(list != null && list.size() > 0){
                        String tableNameStr = StringUtils.join(list, ",");
                        return R.error(202, "没有找到对应的组件，有可能对应的数据库表：" + tableNameStr);
                    }
                }
                if(maps == null || maps.size() == 0){ // 第6次查询
                    QueryWrapper<String> qw6 = new QueryWrapper<>();
                    qw6.likeRight("table_name", ss[1].toUpperCase());
                    List<String> list = queryMapper.queryDBTableName(qw6);
                    if(list != null && list.size() > 0){
                        String tableNameStr = StringUtils.join(list, ",");
                        return R.error(202, "没有找到对应的组件，有可能对应的数据库表：" + tableNameStr);
                    }
                }
            }else{
                return R.error("数据格式错误");
            }
        }
        return R.ok().put("data", maps);
    }

    @Override
    public R queryClasses(String componentId) {
        QueryWrapper<Map<String, Object>> qw = new QueryWrapper<>();
        qw.eq("COMPONENTID",componentId);
        qw.ne("classtype","203");   // 排除枚举
        List<Map<String,Object>> maps = queryMapper.queryClasses(qw);
        return R.ok().put("data", maps);
    }

    @Override
    public R queryPropertys(String classId) {
        QueryWrapper<Map<String, Object>> qw = new QueryWrapper<>();
        qw.eq("classid",classId);
        List<Map<String,Object>> maps = queryMapper.queryPropertys(qw);
        for(Map<String,Object> map : maps){
            String typeName = "";
            String type = "";
            if(map.get("EID") != null){
                typeName = "枚举";
                type = "1";
            }else if(map.get("CID") != null){
                String dataType = String.valueOf(map.get("DATATYPE"));
                if(dataType != null && dataType.length() > 20){
                    // 引用类型
                    typeName = String.valueOf(map.get("CNAME"));
                    type = "2";
                }else if(dataType != null && dataType.length() == 20){
                    // 基础类型
                    typeName = String.valueOf(map.get("CNAME"));
                    type = "3";
                }
            }
            map.put("TYPENAME", typeName);
            map.put("TYPE", type);
        }
        return R.ok().put("data", maps);
    }

    @Override
    public R queryEnums(String id) {
        QueryWrapper<Map<String, Object>> qw = new QueryWrapper<>();
        qw.eq("id",id);
        List<Map<String,Object>> maps = queryMapper.queryEnums(qw);
        return R.ok().put("data", maps);
    }

    @Override
    public R queryClass(String classId) {
        QueryWrapper<Map<String, Object>> qw = new QueryWrapper<>();
        qw.eq("id",classId);
        Map<String,Object> map = queryMapper.queryClass(qw);
        return R.ok().put("data", map);
    }

    @Override
    public R queryClassesByTabName(String tabName) {
        if(tabName != null){
            QueryWrapper<Map<String, Object>> qw = new QueryWrapper<>();
            qw.eq("upper(defaulttablename)", tabName.toUpperCase());
            List<Map<String,Object>> maps = queryMapper.queryClassesByTabName(qw);
            return R.ok().put("data", maps);
        }
        return null;
    }

    @Override
    public R queryTables(String tableName) {
        QueryWrapper<String> qw = new QueryWrapper<>();
        qw.like("table_name", tableName.toUpperCase());
        List<String> maps = queryMapper.queryDBTableName(qw);
        List<Map<String, String>> value = maps.stream().map(item -> {
            Map<String, String> map = new HashMap<>();
            map.put("value", item);
            return map;
        }).collect(Collectors.toList());
        return R.ok().put("data", value);
    }

    @Override
    public R queryTableData(String tableName, int pageSize, int currentPage) {
        int startNum = (currentPage - 1) * pageSize;
        int endNum = currentPage * pageSize;
        int total = queryMapper.queryTableDataCount(tableName);
        if(total > 0){
            List<Map<String, String>> maps = queryMapper.queryTableData(tableName, startNum, endNum);
            maps = maps.stream().map(item->{
                if(item.containsKey("RID")){
                    item.remove("RID");
                }
                return item;
            }).collect(Collectors.toList());
            Map<String, String> map = maps.get(0);
            Set<Map.Entry<String, String>> entries = map.entrySet();
            Set<String> strings = map.keySet();
            List<Map<String, String>> columns = new ArrayList<>();
            for(String s :strings){
                Map<String, String> m = new HashMap<>();
                m.put("prop", s);
                m.put("label", s.toLowerCase());
                columns.add(m);
            }
            return R.ok().put("data", maps).put("columns", columns).put("total", total);
        }else{
            return R.ok().put("data", null);
        }
    }
}
